var host = 'http://47.52.135.227:8080'; //股票

var link = "ws://47.52.135.227:8080/sexp/sexp/webSocketServer?account=''";
var k_server = {
	hang: host + '/sexp/stock/getNewInfo', //行情列表
	line: host + '/sexp/stock/getGoodsInfo' //(minute/minute5/minute15/minute30/minute60/day)
}

var code = GetQueryString('code'); //接受传过来色值
var Kline = {};
Kline.getData = function() {
		$.get(host+'/sexp/stock/getNewInfo', {
			code: code,
			type: 2
		}, function(data) {
			if(data.code == 200) {
				jo.reTpl($('#temp'), {
					data: data.data
				}, $('#cont'));
			}
		})

	},
	Kline.Kline = function() {
		var _state = '';
		var dom = document.getElementById("container");
		var myChart = echarts.init(dom); //canvas绘图
		var app = {};
		option = null;
		var upColor = '#ec0000';
		var downColor = '#00da3c';
		var getUrl = null;
		//分时线专用数据处理函数
		function calcluateMinute(data) {
			var val = [],
				upDown = [],
				percent = [],
				volume = [];

			for(var i = 0; i < data.values.length; i++) {
				val.push(data.values[i][1]);
				volume.push(data.volumes[i][1]);
			}
			minuteArr = {
				time: data.categoryData,
				price: val,
				volume: volume
			}
			return val;

		}

		function splitData(rawData) {
			//数据加工函数 ， 把返回来的数据分为3组数据 分别为categoryData 时间 values股票数据 volumes成交量	
			var categoryData = [];
			var values = [];
			var volumes = [];
			if(_state == 'minute') {
				for(var i = 0; i < rawData.length; i++) {
					categoryData.push(rawData[i].splice(0, 1)[0]);
					values.push(rawData[i]);
					volumes.push([i, rawData[i][4], rawData[i][0] > rawData[i][1] ? 1 : -1]);
					//				console.log(i)
				}
				/*		

						/*var lastTime = categoryData.pop().split(':');
						var shi = lastTime[0];
						var fen = lastTime[1];
						var miao = lastTime[2];
						var time = [];*/
				//for循环 再加100条数据
				/*		for(var k = 0; k < 1; k++) {
							fen++
							fen = fen < 10 ? ('0' + fen) : fen;
							if(fen >= 60) {
								shi++
								fen = 0
							}
							if(fen == 59 && shi == 23) {
								break;
							}
							categoryData.push((shi + ':' + fen + ':00'));
						}*/
				/*	var len = categoryData.length - values.length
					for(var n = 0; n < len; n++) {
						values.push('');
						volumes.push('');
					}*/

				return {
					categoryData: categoryData,
					values: values,
					volumes: volumes
				};

			} else {

				for(var i = 0; i < rawData.length; i++) {
					categoryData.push(rawData[i].splice(0, 1)[0]);
					values.push(rawData[i]);
					volumes.push([i, rawData[i][4], rawData[i][0] > rawData[i][1] ? 1 : -1]);
				}

				return {
					categoryData: categoryData,
					values: values,
					volumes: volumes
				};
			}

		}

		function calculateMA(dayCount, data) { //5分线 10分线 处理函数
			var result = [];
			for(var i = 0, len = data.values.length; i < len; i++) {
				if(i < dayCount) {
					result.push('-');
					continue;
				}
				var sum = 0;
				for(var j = 0; j < dayCount; j++) {
					sum += data.values[i - j][1];
				}
				result.push(+(sum / dayCount).toFixed(3));
			}
			return result;
		}
		//ajax请求 + 数据处理函数  

		function myget(_start, _end, time, code) {
			var okdata = []; //整理后的数据
			$.get(getUrl, {
				action: 'goodsHistoryInfoGet',
				goodsType: time,
				pageSize: 500,
				page: 1,
				code: code
			}, function(data) {
				if(data.code == 200) {
					var rudata = data.data;
					for(var i = 0; i < rudata.length; i++) {
						var onedata = [];
						if(time != 'day') {
							onedata.push(rudata[i].time, Number(rudata[i].openingPrice), Number(rudata[i].closingPrice), Number(rudata[i].highestPrice), Number(rudata[i].lowestPrice), Number(rudata[i].volume));
						} else {
							onedata.push(changeTime(rudata[i].date), Number(rudata[i].openingPrice), Number(rudata[i].closingPrice), Number(rudata[i].highestPrice), Number(rudata[i].lowestPrice), Number(rudata[i].volume));
						}
						okdata.unshift(onedata);
					}

					if(_state == 'minute') {

						share_time(okdata, _start, _end);

					} else {
						long_time(okdata, _start, _end);
					}
					$('#loading').html('加载中...');
					$('#loading').css('display', 'none');
				} else {
					long_time([], 0, 0);
					$('#loading').css('display', 'block');
					$('#loading').html(data.msg);
				}

			})
		}

		//画日K 周k 月k 线处理函数
		function long_time(mydata, _start, _end) {
			//		console.log(mydata);
			var data = splitData(mydata);
			myChart.setOption(option = {
				backgroundColor: '#131E30',
				animation: false,
				legend: {
					top: 10,
					left: 'center',
					data: ['MA5', 'MA10', 'MA20'],
					itemWidth: 5,
					itemHeight: 3,
					textStyle: {
						color: '#999',
						fontSize: 10
					}
				},
				tooltip: {
					axisPointer: {
						type: 'cross'
					},
					backgroundColor: '#12253e',
					borderWidth: 1,
					borderColor: '#595a5b',
					padding: 10,
					textStyle: {
						color: '#fff',
						fontSize: 10
					},
					position: function(pos, params, el, elRect, size) {
						var obj = {
							top: 10
						};
						obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 30;
						return obj;
					}
					// extraCssText: 'width: 170px'
				},
				//小方块字体设置
				axisPointer: {
					link: {
						xAxisIndex: 'all'
					},
					label: {
						backgroundColor: '#12253e'
					}
				},
				visualMap: {
					show: false,
					seriesIndex: 5,
					dimension: 2,
					pieces: [{
						value: 1,
						color: downColor
					}, {
						value: -1,
						color: upColor
					}, {
						value: 0,
						color: '#d4d507'
					}]
				},
				grid: [{
						left: '15%',
						right: '5%',
						top: '15%',
						height: '50%'
					},
					{
						left: '15%',
						right: '5%',
						top: '80%',
						height: '20%'
					}
				],
				xAxis: [{
						type: 'category',
						data: data.categoryData,
						scale: true,
						boundaryGap: false,
						axisLine: {
							onZero: false
						},
						splitLine: {
							show: false
						},
						splitNumber: 20,
						min: 'dataMin',
						max: 'dataMax',
						axisPointer: {
							z: 100
						},
						axisLine: {
							lineStyle: {
								color: '#595a5b',
								width: 1,
							}
						}
					},
					{
						type: 'category',
						gridIndex: 1,
						data: data.categoryData,
						scale: true,
						boundaryGap: false,
						axisLine: {
							onZero: false
						},
						axisTick: {
							show: false
						},
						splitLine: {
							show: false
						},
						axisLabel: {
							show: false
						},
						splitNumber: 20,
						min: 'dataMin',
						max: 'dataMax',
						axisLine: {
							lineStyle: {
								color: '#595a5b',
								width: 1,
							}
						}

					}
				],
				yAxis: [{
						scale: true,
						splitArea: {
							show: false
						},
						axisLine: {
							lineStyle: {
								color: '#595a5b',
								width: 1,
							}
						},
						splitLine: {
							show: false
						}
					},
					{
						scale: false,
						gridIndex: 1,
						splitNumber: 1,
						axisLabel: {
							show: false
						},
						axisLine: {
							show: false
						},
						axisTick: {
							show: false
						},
						splitLine: {
							show: false
						},
					}
				],
				dataZoom: [{
						type: 'inside',
						xAxisIndex: [0, 1],
						start: _start,
						end: _end
					},
					{
						show: false,
						xAxisIndex: [0, 1],
						type: 'slider',
						top: '85%',
						start: _start,
						end: _end
					}
				],
				series: [{
						name: 'Dow-Jones index',
						type: 'candlestick',
						data: data.values,
						itemStyle: {
							normal: {
								color: upColor,
								color0: 'transparent',
								borderColor: null,
								borderColor0: downColor
							}
						},
						tooltip: {
							formatter: function(param) {
								return [
									'时间: ' + param.name + '<hr size=1 style="margin: 3px 0">',
									'开盘: ' + param.data[1] + '<br/>',
									'闭盘: ' + param.data[2] + '<br/>',
									'最高: ' + param.data[3] + '<br/>',
									'最低: ' + param.data[4] + '<br/>',
									'成交量: <span style="color:#f3f301;">' + (param.data[5] / 10000).toFixed(2) + '万</span></br>'
								].join('');
							}
						}
					},

					{
						name: 'MA5',
						type: 'line',
						data: calculateMA(5, data),
						smooth: true,
						lineStyle: {
							normal: {
								opacity: 0.8,
								color: '#980f9a',
								width: 1
							}
						},
						itemStyle: {
							normal: {
								color: '#980f9a'
							}
						}

					},
					{
						name: 'MA10',
						type: 'line',
						data: calculateMA(10, data),
						smooth: true,
						lineStyle: {
							normal: {
								opacity: 0.8,
								width: 1,
								color: 'yellow'
							}
						},

						itemStyle: {
							normal: {
								color: 'yellow'
							}
						}

					},
					{
						name: 'MA20',
						type: 'line',
						data: calculateMA(20, data),
						smooth: true,
						lineStyle: {
							normal: {
								opacity: 0.8,
								width: 1,
								color: '#7bbce9'
							}
						},
						itemStyle: {
							normal: {
								color: '#7bbce9'
							}
						}
					},
					{
						name: '',
						type: 'line',
						//					data: calculateMA(30, data),
						smooth: true,
						lineStyle: {
							normal: {
								opacity: 0
							}
						},
						itemStyle: {
							normal: {
								color: '#fff'
							}
						}
					},
					{
						name: 'Volume',
						type: 'bar',
						xAxisIndex: 1,
						yAxisIndex: 1,
						data: data.volumes
					}
				]
			}, true);

			myChart.dispatchAction({
				type: 'brush',
				areas: [{
					brushType: 'lineX',
					coordRange: ['2016-06-02', '2016-06-20'],
					xAxisIndex: 0
				}]
			});

		}

		function share_time(mydata, _start, _end) {

			var data = splitData(mydata);
			//		console.log(data);
			myChart.setOption(option = {
				backgroundColor: '#131E30',
				animation: false,
				legend: {
					top: 10,
					left: 'center',
					data: ['MA5', 'MA10', 'MA20'],
					itemWidth: 5,
					itemHeight: 3,
					textStyle: {
						color: '#999',
						fontSize: 10
					}
				},
				tooltip: {
					axisPointer: {
						type: 'cross'
					},
					backgroundColor: '12253e',
					borderWidth: 1,
					borderColor: '#595a5b',
					padding: 10,
					textStyle: {
						color: '#fff',
						fontSize: 10
					},
					position: function(pos, params, el, elRect, size) {
						var obj = {
							top: 10
						};
						obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 30;
						return obj;
					}
					// extraCssText: 'width: 170px'
				},
				//小方块字体设置
				axisPointer: {
					link: {
						xAxisIndex: 'all'
					},
					label: {
						backgroundColor: '#12253e'
					}
				},
				visualMap: {
					show: false,
					seriesIndex: 5,
					dimension: 2,
					pieces: [{
						value: 1,
						color: downColor
					}, {
						value: -1,
						color: upColor
					}, {
						value: 0,
						color: '#d4d507'
					}]
				},
				grid: [{
						left: '15%',
						right: '5%',
						top: '15%',
						height: '50%'
					},
					{
						left: '15%',
						right: '5%',
						top: '80%',
						height: '20%'
					}
				],
				xAxis: [{
						type: 'category',
						data: data.categoryData,
						scale: true,
						boundaryGap: false,
						axisLine: {
							onZero: false
						},
						splitLine: {
							show: false
						},
						splitNumber: 20,
						min: 'dataMin',
						max: 'dataMax',
						axisPointer: {
							z: 100
						},
						axisLine: {
							lineStyle: {
								color: '#595a5b',
								width: 1, //这里是为了突出显示加上的  
							}
						}
					},
					{
						type: 'category',
						gridIndex: 1,
						data: data.categoryData,
						scale: true,
						boundaryGap: false,
						axisLine: {
							onZero: false
						},
						axisTick: {
							show: false
						},
						splitLine: {
							show: false
						},
						axisLabel: {
							show: false
						},
						splitNumber: 20,
						min: 'dataMin',
						max: 'dataMax',
						axisLine: {
							lineStyle: {
								color: '#595a5b',
								width: 1,
							}
						}

					}
				],
				yAxis: [{
						scale: true,
						splitArea: {
							show: false
						},
						axisLine: {
							lineStyle: {
								color: '#595a5b',
								width: 1,
							}
						},
						splitLine: {
							show: false
						}
					},
					{
						scale: false,
						gridIndex: 1,
						splitNumber: 1,
						axisLabel: {
							show: false
						},
						axisLine: {
							show: false
						},
						axisTick: {
							show: false
						},
						splitLine: {
							show: false
						},
					}
				],
				dataZoom: [{
						type: 'inside',
						xAxisIndex: [0, 1],
						start: _start,
						end: _end
					},
					{
						show: false,
						xAxisIndex: [0, 1],
						type: 'slider',
						top: '85%',
						start: _start,
						end: _end
					}
				],
				series: [{
						name: '',
						type: 'candlestick',
						data: '',
						itemStyle: {
							normal: {
								color: upColor,
								color0: downColor,
								borderColor: null,
								borderColor0: null
							}
						}
					},
					{
						name: '价格',
						trigger: 'item',
						type: 'line',
						data: calcluateMinute(data),
						smooth: true,
						tooltip: {
							formatter: function(param) {
								var ind = param.dataIndex;
								//昨日收盘价
								var closePrice = Number($('.closeCur').html());
								//									var percent = Number(minuteArr.percent[ind]); //幅度 
								//									var upDown = Number(minuteArr.upDown[ind]); //涨跌
								var priceDom = '',
									upDom = '',
									percentDom = '';
								//价格  
								if(param.data > closePrice) {
									priceDom = '<span style="color:' + upColor + '">' + param.data + '</span>'
								} else if(param.data < closePrice) {
									priceDom = '<span style="color:' + downColor + '">' + param.data + '</span>'
								} else {
									priceDom = '<span style="color:#fff">' + param.data + '</span>'
								}
								/*//涨跌
								if(upDown > 0) {
									upDom = '<span style="color:' + upColor + '">' + upDown + '</span>'
								} else if(upDown < 0) {
									upDom = '<span style="color:' + downColor + '">' + upDown + '</span>'
								} else {
									upDom = '<span style="color:#fff">' + upDown + '</span>'
								}
								//幅度
								if(percent > 0) {
									percentDom = '<span style="color:' + upColor + '">' + percent + '%</span>'
								} else if(upDown < 0) {
									percentDom = '<span style="color:' + downColor + '">' + percent + '%</span>'
								} else {
									percentDom = '<span style="color:#fff">' + percent + '%</span>'
								}*/
								//交易量
								//									minuteArr.volume[ind] = (minuteArr.volume[ind] >= 100000) ? (minuteArr.volume[ind] / 10000).toFixed(2) + '万' : minuteArr.volume[ind];

								return [
									'<span style="text-align:center;margin-bottom:3px;">' + minuteArr.time[ind] + '</span><br/>',
									'价格: ' + param.data + '<br/>',
									//								'涨跌: ' + 33 + '<br/>',
									//								'幅度: ' + 333 + '<br/>',
									'成交: <span style="color:#f3f301;">' + minuteArr.volume[ind] + '</span>'
								].join('');
							}
						},
						lineStyle: {
							normal: {
								width: 1,
								opacity: 1
							}
						},
						areaStyle: {
							normal: {
								color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
									offset: 0,
									color: 'rgba(47, 132, 204,0.2)' //颜色更改
								}])
							}
						},
						itemStyle: {
							normal: {
								color: '#c0c0c1'
							}
						}
					},
					{
						name: '涨跌',
						type: 'line',
						data: '',
						smooth: true,
						lineStyle: {
							normal: {
								opacity: 1
							}
						},
						itemStyle: {
							normal: {
								color: '#f3f301'
							}
						}
					},
					{
						name: '幅度',
						type: 'line',
						data: '',
						smooth: true,
						lineStyle: {
							normal: {
								opacity: 1
							}
						},
						itemStyle: {
							normal: {
								color: '#7bbce9'
							}
						}
					},
					{
						name: '',
						type: 'line',
						data: '',
						smooth: true,
						lineStyle: {
							normal: {
								opacity: 1
							}
						},
						itemStyle: {
							normal: {
								color: 'transparent',
								label: {
									show: false,
									color: 'white',
									fontSize: '12'
								}
							}
						}
					},
					{
						name: '成交量',
						type: 'bar',
						xAxisIndex: 1,
						yAxisIndex: 1,
						data: data.volumes
					}
				]
			}, true);

			myChart.dispatchAction({
				type: 'brush',
				areas: [{
					brushType: 'lineX',
					coordRange: ['2016-06-02', '2016-06-20'],
					xAxisIndex: 0
				}]
			});

		}

		//*********************/
		if(option && typeof option === "object") {
			myChart.setOption(option, true);
		}
		var code = GetQueryString('code');
		var setm = '';
		if(code == 'CAR-T' || code == 'AI') {
			getUrl = k_server2.line;
		} else {
			getUrl = k_server.line;
		}

		function mysett() {
			myget(90, 100, 'minute', code);
			_state = 'minute';
		}
		$('#nav_change_time li').on('click', function() {
			$('#loading').css('display', 'block');
			$(this).addClass('line').siblings('li').removeClass('line');
			var id = $(this).attr('data-id');
			switch(id) {
				case '1':
					mysett();
					setm = setInterval(mysett, 30000);
					break;
				case '2':
					clearInterval(setm);
					myget(95, 100, 'minute15', code);
					_state = 'nominute';
					break;
				case '3':
					clearInterval(setm);
					myget(95, 100, 'minute30', code);
					_state = 'nominute';
					break;
				case '4':
					clearInterval(setm);
					myget(95, 100, 'minute60', code);
					_state = 'nominute';
					break;
				case '5':
					clearInterval(setm);
					myget(50, 100, 'day', code);
					_state = 'nominute';
					break;
			}

		})

		myget(90, 100, 'minute', code);
		_state = 'minute';
		setm = setInterval(mysett, 30000);

	},
	//推送
	Kline.tuiSong = function() {
		var websocket;
		var dom = {};
		var domarray = [],
			codearray = [],
			jiagearray = [],
			fuduanarray = [];

		//		链接长链接

		if('WebSocket' in window) {
			websocket = new WebSocket(link);
		} else if('MozWebSocket' in window) {
			websocket = new MozWebSocket(link);
		}
		//打开长连接
		websocket.onopen = function() {
			var msg = {
				type: "vb_okex"
			};
			// 发送消息
			websocket.send(JSON.stringify(msg));
			setTimeout(function() {
				dom = {
					price: $('#nowprice'),
					hight: $('#hight'),
					low: $('#low'),
					fudu: $('#fudu')
				}
			}, 0)
		};
		//数据处理
		websocket.onmessage = function(evnt) {
			var datanum = JSON.parse(evnt.data);			
			if(datanum.code == code) {
				dom.fudu.html(datanum.changePercentage);
				dom.price.html(Number(datanum.price).toFixed(4)); //当前价
				dom.hight.html(Number(datanum.high).toFixed(4)); //最高价
				dom.low.html(Number(datanum.low).toFixed(4)); //最低价
				if(datanum.change >= 0) {
					$('#nowprice,#fudu').addClass('upcolor').removeClass('downcolor');
				} else {
					$('#nowprice,#fudu').addClass('downcolor').removeClass('upcolor');
				}
			}
		}
	}
//页面之间传值函数
function GetQueryString(name) {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
	var r = window.location.search.substr(1).match(reg);
	if(r != null) return decodeURI(r[2]);
	return 'eth_usdt';
	//return null;
}

//时间撮转化为时间 函数
function changeTime(data) {
	var date = new Date(data);
	Y = date.getFullYear() + '/';
	M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '/';
	D = date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate();
	/*h = date.getHours() + ':';
	m = date.getMinutes() + ':';
	s = date.getSeconds();*/
	return Y + M + D;

}